package com.majie.algorithm.queue;


import java.util.Arrays;

/**
 * 循环队列
 */
public class CircleQueue<E> {

    private int size;

    private E[] elements;

    private int front;

    private static final int DEFAULT_CAPACITY = 10;

    public CircleQueue( ) {
        this.elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    public int size( ) {
        return size;
    }

    public boolean isEmpty( ) {
        return size == 0;
    }

    public void enQueue(E element) {
        ensureCapacity(size + 1);
        elements[(front + size) % elements.length] = element;
        size++;
    }

    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) {
            return;
        }
        int newCapacity = DEFAULT_CAPACITY + DEFAULT_CAPACITY >> 1;
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[(i + front) % elements.length];
        }
        elements = newElements;
        front = 0;
    }

    public E deQueue( ) {
        E frontElement = elements[front];
        elements[front] = null;
        front = (front + 1) % elements.length;
        size--;
        return frontElement;
    }

    public E front( ) {
        return elements[front];
    }

    @Override
    public String toString( ) {
        StringBuilder sb = new StringBuilder();
        sb.append("capacity=")
                .append(elements.length)
                .append(" size=").append(size)
                .append(" front=").append(front)
                .append(" ,[");
        for (int i = 0; i < elements.length; i++) {
            if (i != 0) {
                sb.append(", ");
            }
            sb.append(elements[i]);
        }
        sb.append("]");
        return sb.toString();
    }

    public static void main(String[] args) {
        CircleQueue<Integer> circle = new CircleQueue<>();
        for (int i = 0; i < 10; i++) {
            circle.enQueue(i);
        }
        System.out.println(circle);
    }
}
